<template>
  <div class="main">
    <div class="part">
      <div class="p-title">
        <div class="title">用户分析</div>
        <div class="search">
          <myDestSelect ref="destSelectRef" @destChange="destChange" />
          <myDateRangeSelect
            ref="dateSelectRef"
            @dateRangeChange="dateRangeChange"
          />
        </div>
      </div>
      <div class="p-cont p-cont-first">
        <div class="drug">
          <div class="title">
            用药管理用户总数（人）
            <span>{{
              userAnalysis && userAnalysis.medicationManagementCount
            }}</span>
            <MyToolTip
              content="指标定义：截止到筛选日期末，加入“用药管理计划”并正常享受该服务的用户数量。\n统计范围：所有来自万户医学院App、公众号内的所有状态正常的预约计划单"
            />
          </div>
          <div class="user-panel">
            <div
              :class="[
                'up-item',
                drugSelectedPanel.includes(1) ? 'active' : ''
              ]"
              @click="changeDrugSelectedPanel(1)"
            >
              <div class="up-des">
                <span>预约服务（人次）</span>
                <MyToolTip
                  content="指标定义：筛选时间内，预约过用药管理服务的人次总数。\n统计范围：所有来自万户医学院App、公众号内的所有状态正常的预约计划单。"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.reservationServiceCount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div
              :class="[
                'up-item',
                drugSelectedPanel.includes(2) ? 'active' : ''
              ]"
              @click="changeDrugSelectedPanel(2)"
            >
              <div class="up-des">
                <span>新用户 (人)</span>
                <MyToolTip
                  content="指标定义：筛选时间内，首次加入“用药管理计划”服务的用户数量之和。\n统计范围：所有来自万户医学院App、公众号内的预约计划单，剔除曾经或正在使用的用户，确保用户首次使用。"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.newMedicationManagementCount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="red"
                  />
                  <span class="red">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div
              :class="[
                'up-item',
                drugSelectedPanel.includes(3) ? 'active' : ''
              ]"
              @click="changeDrugSelectedPanel(3)"
            >
              <div class="up-des">
                <span>完成取药用户（人次）</span>
                <MyToolTip
                  content="指标定义：筛选时间内，配送正常完成取得药品包裹的用户人次数量之和。\n统计范围：所有来自万户医学院App、公众号的订单；不剔除退款订单"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.completeOrderCount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div
              :class="[
                'up-item',
                drugSelectedPanel.includes(4) ? 'active' : ''
              ]"
              @click="changeDrugSelectedPanel(4)"
            >
              <div class="up-des">
                <span>规律用药用户 (人次)</span>
                <MyToolTip
                  content="指标定义：筛选时间内，完成取药并且取药行为符合其所属中心药房设定的规律用药规则的用户人次数量之和。\n统计范围：所有来自万户医学院App、公众号的订单；不剔除退款订单"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.regularMedicationCount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
          </div>
        </div>
        <div class="trend">
          <!-- <div class="title">趋势分析(人)</div> -->
          <div class="trend-content">
            <div class="tc-left">
              <div class="tc-btn">
                <el-button type="primary">导出详情数据</el-button>
                <el-button-group class="ml-4">
                  <el-button
                    plain
                    :type="drugDataTimeType === 1 ? 'primary' : 'default'"
                    @click="changeDrugDataTimeType(1)"
                    >按日</el-button
                  >
                  <el-button
                    plain
                    :type="drugDataTimeType === 2 ? 'primary' : 'default'"
                    @click="changeDrugDataTimeType(2)"
                    >按周</el-button
                  >
                  <el-button
                    plain
                    :type="drugDataTimeType === 3 ? 'primary' : 'default'"
                    @click="changeDrugDataTimeType(3)"
                    >按月</el-button
                  >
                </el-button-group>
              </div>

              <div class="tc-line" ref="drugTrendLineRef" />
            </div>
            <div class="tc-right">
              <div class="trend-pie" ref="drugTrendPieRef" />
            </div>
          </div>
        </div>
      </div>

      <div class="p-cont">
        <div class="drug">
          <div class="title">
            销售统计
            <!-- <span>17126</span> -->
          </div>
          <div class="user-panel">
            <div
              :class="[
                'up-item',
                saleSelectedPanel.includes(1) ? 'active' : ''
              ]"
              @click="changeSaleSelectedPanel(1)"
            >
              <div class="up-des">
                <span>订单成交 (个)</span>
                <MyToolTip
                  content="指标定义：筛选时间内，已支付成功的订单数之和\n统计范围：所有来自万户医学院App、公众号的订单；不剔除退款订单"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.orderSaleCount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div
              :class="[
                'up-item',
                saleSelectedPanel.includes(2) ? 'active' : ''
              ]"
              @click="changeSaleSelectedPanel(2)"
            >
              <div class="up-des">
                <span>销售额 (元)</span>
                <MyToolTip
                  content="指标定义：筛选时间内，所有成交订单的实收金额之和\n统计范围：所有来自万户医学院App、公众号的订单；不剔除退款金额"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.orderSaleAmount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="red"
                  />
                  <span class="red">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div
              :class="[
                'up-item',
                saleSelectedPanel.includes(3) ? 'active' : ''
              ]"
              @click="changeSaleSelectedPanel(3)"
            >
              <div class="up-des">
                <span>订单退款 (个)</span>
                <MyToolTip
                  content="指标定义：筛选时间内，完成退款的订单数之和\n统计范围：所有来自万户医学院App、公众号的退货订单"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.orderRefundCount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div
              :class="[
                'up-item',
                saleSelectedPanel.includes(4) ? 'active' : ''
              ]"
              @click="changeSaleSelectedPanel(4)"
            >
              <div class="up-des">
                <span>退款额 (元)</span>
                <MyToolTip
                  content="指标定义：筛选时间内，所有退款订单的退回金额之和\n统计范围：所有来自万户医学院App、公众号的退货订单"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.orderRefundAmount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
          </div>
        </div>
        <div class="trend">
          <!-- <div class="title">趋势分析</div> -->
          <div class="trend-content">
            <div class="tc-single">
              <div class="tc-btn">
                <el-button type="primary">导出详情数据</el-button>
                <el-button-group class="ml-4">
                  <el-button
                    plain
                    :type="saleDataTimeType === 1 ? 'primary' : 'default'"
                    @click="changeSaleDataTimeType(1)"
                    >按日</el-button
                  >
                  <el-button
                    plain
                    :type="saleDataTimeType === 2 ? 'primary' : 'default'"
                    @click="changeSaleDataTimeType(2)"
                    >按周</el-button
                  >
                  <el-button
                    plain
                    :type="saleDataTimeType === 3 ? 'primary' : 'default'"
                    @click="changeSaleDataTimeType(3)"
                    >按月</el-button
                  >
                </el-button-group>
              </div>

              <div class="tc-line" ref="sellLineBarRef" />
            </div>
          </div>
        </div>
      </div>
      <div class="p-cont">
        <div class="drug">
          <div class="title">
            收入统计
            <!-- <span>17126</span> -->
          </div>
          <div class="user-panel">
            <div
              :class="[
                'up-item',
                incomeSelectedPanel.includes(1) ? 'active' : ''
              ]"
              @click="changeIncomeSelectedPanel(1)"
            >
              <div class="up-des">
                <span>医保收款 (元)</span>
                <MyToolTip
                  content="指标定义：筛选时间内，以医保在线结算的方式收取的金额之和\n统计范围：所有来自万户医学院App、公众号的订单；不剔除退款金额"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.miSaleAmount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div
              :class="[
                'up-item',
                incomeSelectedPanel.includes(2) ? 'active' : ''
              ]"
              @click="changeIncomeSelectedPanel(2)"
            >
              <div class="up-des">
                <span>自费收款 (元)</span>
                <MyToolTip
                  content="指标定义：筛选时间内，以微信、支付宝等在线支付的方式实收的金额之和\n统计范围：所有来自万户医学院App、公众号的订单；不剔除退款金额"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.selfSaleAmount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="red"
                  />
                  <span class="red">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div
              :class="[
                'up-item',
                incomeSelectedPanel.includes(3) ? 'active' : ''
              ]"
              @click="changeIncomeSelectedPanel(3)"
            >
              <div class="up-des">
                <span>医保退款 (元)</span>
                <MyToolTip
                  content="指标定义：筛选时间内，以医保在线结算的方式退回的金额之和\n统计范围：所有来自万户医学院App、公众号的退货订单"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.miRefundAmount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div
              :class="[
                'up-item',
                incomeSelectedPanel.includes(4) ? 'active' : ''
              ]"
              @click="changeIncomeSelectedPanel(4)"
            >
              <div class="up-des">
                <span>自费退款 (元)</span>
                <MyToolTip
                  content="指标定义：筛选时间内，以微信、支付宝等在线支付的方式退回的金额之和\n统计范围：所有来自万户医学院App、公众号的退货订单"
                />
              </div>
              <div class="up-num">
                {{ userAnalysis && userAnalysis.selfRefundAmount }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
          </div>
        </div>
        <div class="trend">
          <!-- <div class="title">趋势分析</div> -->
          <div class="trend-content">
            <div class="tc-single">
              <div class="tc-btn">
                <el-button type="primary">导出详情数据</el-button>
                <el-button-group class="ml-4">
                  <el-button
                    plain
                    :type="inComeDataTimeType === 1 ? 'primary' : 'default'"
                    @click="changeIncomeDataTimeType(1)"
                    >按日</el-button
                  >
                  <el-button
                    plain
                    :type="inComeDataTimeType === 2 ? 'primary' : 'default'"
                    @click="changeIncomeDataTimeType(2)"
                    >按周</el-button
                  >
                  <el-button
                    plain
                    :type="inComeDataTimeType === 3 ? 'primary' : 'default'"
                    @click="changeIncomeDataTimeType(3)"
                    >按月</el-button
                  >
                </el-button-group>
              </div>

              <div class="tc-line" ref="incomeLineRef" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, ref, Ref, onUnmounted, reactive } from "vue";

import { useECharts } from "@pureadmin/utils";
import * as echartsTypes from "echarts/types/dist/echarts";
// 地区选择控件
import myDestSelect, { destSelectType } from "@/components/myDestSelect.vue";
import myDateRangeSelect, {
  dateRangeType
} from "@/components/myDateRangeSelect.vue";
import { getUserAnalysis, getUserTrendAnalysis } from "@/api/supply";
import { formatDate, lastWeeks } from "@/utils/tools";
import MyToolTip from "@/components/myToolTip.vue";
const destSelectRef = ref<destSelectType | null>(null);
const dateSelectRef = ref<dateRangeType>();

const drugTrendLineRef = ref(null);
const drugTrendPieRef = ref(null);
const sellLineBarRef = ref(null);
const incomeLineRef = ref(null);

let drugTrendLineIns = null;
let drugTrendPieIns = null;
let sellLineBarIns = null;
let incomeLineIns = null;

// 类型 1=按日 2=按周 3=按月
const drugDataTimeType = ref(1);
const saleDataTimeType = ref(1);
const inComeDataTimeType = ref(1);

enum drugSelectedType {
  reservationServiceCount = 1,
  newMedicationManagementCount,
  completeOrderCount,
  regularMedicationCount
}

enum saleSelectedType {
  orderSaleCount = 1,
  orderSaleAmount,
  orderRefundCount,
  orderRefundAmount
}
enum incomeSelectedType {
  miSaleAmount = 1,
  selfSaleAmount,
  miRefundAmount,
  selfRefundAmount
}
const drugSelectedPanel = reactive([1]);
const saleSelectedPanel = reactive([1]);
const incomeSelectedPanel = reactive([1]);

function changeDrugSelectedPanel(val) {
  // const index = drugSelectedPanel.indexOf(val);
  // if (index > -1) {
  //   if (drugSelectedPanel.length === 1) {
  //     return;
  //   } else {
  //     drugSelectedPanel.splice(index, 1);
  //   }
  // } else {
  //   drugSelectedPanel.push(val);
  // }
  drugSelectedPanel.splice(0, 1, val);
  setDrugTrendLineOption();
}

function changeSaleSelectedPanel(val) {
  // const index = saleSelectedPanel.indexOf(val);
  // if (index > -1) {
  //   if (saleSelectedPanel.length === 1) {
  //     return;
  //   }
  //   saleSelectedPanel.splice(index, 1);
  // } else {
  //   saleSelectedPanel.push(val);
  // }
  saleSelectedPanel.splice(0, 1, val);
  setSaleTrendLineOption();
}

function changeIncomeSelectedPanel(val) {
  // const index = incomeSelectedPanel.indexOf(val);
  // if (index > -1) {
  //   if (incomeSelectedPanel.length === 1) {
  //     return;
  //   }
  //   incomeSelectedPanel.splice(index, 1);
  // } else {
  //   incomeSelectedPanel.push(val);
  // }
  incomeSelectedPanel.splice(0, 1, val);
  setIncomeLineOption();
}

const drugTrendData = ref({
  xAixsData: [],
  reservationServiceCount: [],
  newMedicationManagementCount: [],
  completeOrderCount: [],
  regularMedicationCount: []
});
const saleTrendData = ref({
  xAixsData: [],
  orderSaleCount: [],
  orderSaleAmount: [],
  orderRefundCount: [],
  orderRefundAmount: []
});
const incomeTrendData = ref({
  xAixsData: [],
  miSaleAmount: [],
  selfSaleAmount: [],
  miRefundAmount: [],
  selfRefundAmount: []
});

function changeDrugDataTimeType(val) {
  console.log("val:", val);
  drugDataTimeType.value = val;
  getUserTrendAnalysisData("drug");
}
function changeSaleDataTimeType(val) {
  console.log("val:", val);
  saleDataTimeType.value = val;
  getUserTrendAnalysisData("sale");
}

function changeIncomeDataTimeType(val) {
  console.log("val:", val);
  inComeDataTimeType.value = val;
  getUserTrendAnalysisData("income");
}

const drugTrendOption = {
  title: {
    text: "趋势分析(人)",
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },

  legend: {
    data: ["预约服务", "新用户", "完成取药用户", "规律用药用户"]
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    top: "20%",
    containLabel: true
  },

  xAxis: {
    type: "category",
    data: []
  },
  yAxis: {
    type: "value"
  },
  series: [
    {
      name: "预约服务",
      type: "line",
      data: []
    }
  ]
};

function initDrugTrendLine(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(drugTrendOption as any);
  return getInstance();
}

function setDrugTrendLineOption() {
  // 获取数据
  const textNames = ["预约服务", "新用户", "完成取药用户", "规律用药用户"];
  drugTrendOption.legend.data = drugSelectedPanel.map(item => {
    return textNames[item - 1];
  });
  drugTrendOption.xAxis.data = drugTrendData.value.xAixsData;
  const unitList = ["人次", "人", "人次", "人次"];
  const unit = unitList[drugSelectedPanel[0] - 1];
  drugTrendOption.title.text = `趋势分析 (${unit})`;

  drugTrendOption.series = drugSelectedPanel.map(item => {
    // console.log("drugSelectedType[item]:", drugSelectedType[item]);
    return {
      name: textNames[item - 1],
      type: "line",
      data: drugTrendData.value[drugSelectedType[item]]
    };
  });
  drugTrendLineIns.clear();
  drugTrendLineIns.setOption(drugTrendOption as any);
}

const drugTrendPieOption = {
  title: {
    text: "规律用药比例",
    left: "center",
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },
  legend: {
    orient: "vertical",
    left: "left"
  },
  series: [
    {
      name: "规律用药比例",
      type: "pie",
      radius: "50%",
      data: [
        { value: 1048, name: "规律" },
        { value: 735, name: "不规律" }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)"
        }
      }
    }
  ]
};
function initDrugTrendPie(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(drugTrendPieOption as any);
  return getInstance();
}

function setDrugTrendPieOption() {
  // 获取数据
  // const textNames = ["规律", "不规律"];
  drugTrendPieOption.series[0].data = [
    { value: drugTrendData.value.regularMedicationCount[0], name: "规律" },
    {
      value:
        drugTrendData.value.reservationServiceCount[0] -
        drugTrendData.value.regularMedicationCount[0],
      name: "不规律"
    }
  ];
  drugTrendPieIns.clear();
  drugTrendPieIns.setOption(drugTrendPieOption as any);
}
const saleTrendLineBarOption = {
  title: {
    text: "趋势分析",
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    top: "20%",
    containLabel: true
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },

  legend: {
    data: []
  },
  xAxis: [
    {
      type: "category",
      data: []
    }
  ],
  yAxis: [
    {
      type: "value",
      axisLabel: {
        formatter: "{value}"
      }
    }
  ],
  series: [
    {
      name: "订单成交个数",
      type: "line",
      data: [1, 3, 5, 7]
    }
  ]
};

function initSaleTrendLineBar(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(saleTrendLineBarOption as any);
  return getInstance();
}

function setSaleTrendLineOption() {
  const textNames = ["订单成交个数", "销售额", "订单退款个数", "退款额"];

  saleTrendLineBarOption.legend.data = saleSelectedPanel.map(item => {
    return textNames[item - 1];
  });
  const unitList = ["个", "元", "个", "元"];
  const unit = unitList[saleSelectedPanel[0] - 1];
  saleTrendLineBarOption.title.text = `趋势分析 (${unit})`;

  saleTrendLineBarOption.xAxis[0].data = saleTrendData.value.xAixsData;

  saleTrendLineBarOption.series = saleSelectedPanel.map(item => {
    const key = saleSelectedType[item];
    // if (key === "orderSaleCount" || key === "orderRefundCount") {
    //   return {
    //     name: textNames[item - 1],
    //     type: "line",
    //     data: saleTrendData.value[key]
    //   };
    // } else {
    //   return {
    //     name: textNames[item - 1],
    //     type: "bar",
    //     data: saleTrendData.value[key]
    //   };
    // }
    return {
      name: textNames[item - 1],
      type: "line",
      data: saleTrendData.value[key]
    };
  });
  sellLineBarIns.clear();
  sellLineBarIns.setOption(saleTrendLineBarOption as any);
}

const incomeLineOption = {
  title: {
    text: "趋势分析 (元)",
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
    top: "20%"
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },

  legend: {
    data: []
  },
  xAxis: {
    type: "category",
    data: []
  },
  yAxis: [
    {
      type: "value",
      name: "元",
      nameLocation: "end",
      axisLabel: {
        formatter: "{value} 元"
      }
    }
  ],
  series: [
    {
      name: "",
      type: "line",
      data: []
    }
  ]
};
function initIncomeLine(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(incomeLineOption as any);
  return getInstance();
}

function setIncomeLineOption() {
  const textNames = ["医保收款", "自费收款", "医保退款", "自费退款"];
  incomeLineOption.legend.data = incomeSelectedPanel.map(item => {
    return textNames[item - 1];
  });
  incomeLineOption.xAxis.data = incomeTrendData.value.xAixsData;

  incomeLineOption.series = incomeSelectedPanel.map(item => {
    const key = incomeSelectedType[item];
    return {
      name: textNames[item - 1],
      type: "line",
      data: incomeTrendData.value[key]
    };
  });
  incomeLineIns.clear();
  incomeLineIns.setOption(incomeLineOption as any);
}

function initEcharts() {
  drugTrendLineIns = initDrugTrendLine(drugTrendLineRef);
  drugTrendPieIns = initDrugTrendPie(drugTrendPieRef);
  sellLineBarIns = initSaleTrendLineBar(sellLineBarRef);
  incomeLineIns = initIncomeLine(incomeLineRef);
}
function setEchartOption() {
  setDrugTrendLineOption();
  // 饼图
  setDrugTrendPieOption();
  // 销售
  setSaleTrendLineOption();
  setIncomeLineOption();
}
// 用药管理用户总数
const userAnalysis = ref();
const userTrendAnalysis = ref({
  sections: lastWeeks,
  reservationServiceCount: [], //预约服务 (人次)
  newMedicationManagementCount: [], //新用户 (人)
  completeOrderCount: [], //完成取药用户（人次）
  regularMedicationCount: [], //规律取药用户 (人次)
  orderSaleCount: [], //订单成交 (个)
  orderSaleAmount: [], //销售额 (元)
  orderRefundCount: [], //订单退款 (个)
  orderRefundAmount: [], //退款额 (元)
  miSaleAmount: [], //医保收款 (元)
  selfSaleAmount: [], //自费收款 (元)
  miRefundAmount: [], //医保退款 (元)
  selfRefundAmount: [] //自费退款(元)
});

function resizeChart() {
  // console.log("resizeChart");
  drugTrendLineIns?.resize();
  drugTrendPieIns?.resize();
  sellLineBarIns?.resize();
  incomeLineIns?.resize();
}

async function getUserStaticAnalysisData() {
  const cityId = destSelectRef.value.userSelectedRegions.cityId;
  const areaId = destSelectRef.value.userSelectedRegions.areaId;
  const baseUserSelectedRegions: Record<
    "provinceId" | "cityId" | "areaId",
    string
  > = {
    provinceId: destSelectRef.value.userSelectedRegions.provinceId,
    cityId,
    areaId
  };

  userAnalysis.value = await getUserAnalysis({
    ...baseUserSelectedRegions,
    startDate: formatDate(
      dateSelectRef.value && dateSelectRef.value.dateRangeValue[0]
    ),
    endDate: formatDate(
      dateSelectRef.value && dateSelectRef.value.dateRangeValue[1]
    )
  });
}

async function getUserTrendAnalysisData(dType) {
  const cityId = destSelectRef.value.userSelectedRegions.cityId;
  const areaId = destSelectRef.value.userSelectedRegions.areaId;
  const baseUserSelectedRegions: Record<
    "provinceId" | "cityId" | "areaId",
    string
  > = {
    provinceId: destSelectRef.value.userSelectedRegions.provinceId,
    cityId,
    areaId
  };
  let type = 1;
  if (dType === "drug") {
    type = drugDataTimeType.value;
  } else if (dType === "sale") {
    type = saleDataTimeType.value;
  } else {
    type = inComeDataTimeType.value;
  }
  // console.log("dType:", dType);
  // 获取趋势数据
  userTrendAnalysis.value = (await getUserTrendAnalysis({
    ...baseUserSelectedRegions,
    type: type,
    startDate: formatDate(
      dateSelectRef.value && dateSelectRef.value.dateRangeValue[0]
    ),
    endDate: formatDate(
      dateSelectRef.value && dateSelectRef.value.dateRangeValue[1]
    )
  })) as any;
  if (dType === "all") {
    setDrugTrendData();
    setSaleTrendData();
    setIncomeTrendData();
  } else if (dType === "drug") {
    setDrugTrendData();
  } else if (dType === "sale") {
    setSaleTrendData();
  } else if (dType === "income") {
    setIncomeTrendData();
  }
}

function setDrugTrendData() {
  const xAixsData = userTrendAnalysis.value?.sections.map(item => {
    if (item.indexOf("/") > -1) {
      return item.split("/")[0];
    } else {
      return item;
    }
  });
  drugTrendData.value = {
    xAixsData,
    reservationServiceCount: userTrendAnalysis.value.reservationServiceCount,
    newMedicationManagementCount:
      userTrendAnalysis.value.newMedicationManagementCount,
    completeOrderCount: userTrendAnalysis.value.completeOrderCount,
    regularMedicationCount: userTrendAnalysis.value.regularMedicationCount
  };
  setDrugTrendLineOption();
  setDrugTrendPieOption();
}
function setSaleTrendData() {
  const xAixsData = userTrendAnalysis.value?.sections.map(item => {
    if (item.indexOf("/") > -1) {
      return item.split("/")[0];
    } else {
      return item;
    }
  });
  saleTrendData.value = {
    xAixsData,
    orderSaleCount: userTrendAnalysis.value.orderSaleCount,
    orderSaleAmount: userTrendAnalysis.value.orderSaleAmount,
    orderRefundCount: userTrendAnalysis.value.orderRefundCount,
    orderRefundAmount: userTrendAnalysis.value.orderRefundAmount
  };
  setSaleTrendLineOption();
}
function setIncomeTrendData() {
  const xAixsData = userTrendAnalysis.value?.sections.map(item => {
    if (item.indexOf("/") > -1) {
      return item.split("/")[0];
    } else {
      return item;
    }
  });
  incomeTrendData.value = {
    xAixsData,
    miSaleAmount: userTrendAnalysis.value.miSaleAmount,
    selfSaleAmount: userTrendAnalysis.value.selfSaleAmount,
    miRefundAmount: userTrendAnalysis.value.miRefundAmount,
    selfRefundAmount: userTrendAnalysis.value.selfRefundAmount
  };
  setIncomeLineOption();
}

async function getServerData() {
  getUserStaticAnalysisData();
  getUserTrendAnalysisData("all");
}

function destChange() {
  getServerData();
}

function dateRangeChange() {
  getServerData();
}

onMounted(async () => {
  initEcharts();
  getServerData();

  // setEchartOption 已经包含在getServerData中
  // setEchartOption();

  window.addEventListener("resize", resizeChart);
});
onUnmounted(() => {
  window.removeEventListener("resize", resizeChart);
});
</script>
<style scoped lang="scss">
.main {
  .part {
    background-color: transparent;
    padding: 0 !important;

    .p-title {
      background: white;
      padding: 20px 20px 0px 20px;
      border-radius: 4px;
    }
  }
}

.search {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .el-select {
    margin-right: 20px;
  }

  .el-date-picker {
    margin-left: 20px;
  }
}

.p-cont {
  background-color: white;
  padding: 20px;

  &.p-cont-first {
    margin-top: 0px !important;
  }

  .drug {
    .title {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      display: flex;
      align-items: center;

      span {
        font-size: 24px;
      }
    }

    .user-panel {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 20px;

      .up-item {
        border: 1px solid #eee;
        border-radius: 8px;
        width: 24%;
        padding: 20px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;
        height: 148px;

        &.active {
          background-color: #4993fa;

          .up-des {
            color: white;
          }

          .up-num {
            color: white;
          }

          .up-inc {
            color: white;
          }
        }

        .up-des {
          font-size: 16px;
          color: #333;
          font-weight: 400;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }

        .up-num {
          font-weight: bold;
          font-size: 36px;
          margin-top: 10px;
          color: #333;
        }

        .up-inc {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 10px;
          font-size: 14px;
          color: #666;
          font-weight: 400;

          .up-inc-left {
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #bbb;

            svg {
              width: 16px;
              height: 16px;
              margin: 0px 2px;
            }

            .green {
              color: #00a870;
            }

            .red {
              color: #e54d59;
            }
          }

          .up-inc-right {
            cursor: pointer;
            color: #bbb;
          }
        }
      }
    }
  }

  .trend {
    margin-top: 20px;

    .trend-content {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .tc-single {
        width: 100%;
      }

      .tc-left {
        width: 70%;
      }

      .tc-btn {
        text-align: left;
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
      }

      .tc-line {
        width: 100%;
        height: 400px;
        margin-top: 20px;
      }

      .tc-right {
        width: calc(30% - 20px);
        box-sizing: border-box;
        padding-top: 55px;
        border-left: 1px solid #eee;
        margin-top: 20px;
        margin-left: 20px;

        .trend-pie {
          width: 100%;
          height: 400px;
          box-sizing: border-box;
          padding-left: 20px;
        }
      }
    }
  }
}
</style>
